package org.jeecg.modules.htxincailiao.im.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.CryptoUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.htxincailiao.account.constant.HTAccountTypeEnum;
import org.jeecg.modules.htxincailiao.account.entity.HTPlatformUser;
import org.jeecg.modules.htxincailiao.account.service.IHTAccountService;
import org.jeecg.modules.htxincailiao.im.domain.dto.IMConversationDTO;
import org.jeecg.modules.htxincailiao.im.entity.IMConversation;
import org.jeecg.modules.htxincailiao.im.entity.IMUser;
import org.jeecg.modules.htxincailiao.im.service.IIMConversationService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.htxincailiao.im.service.IIMUserService;
import org.jeecg.modules.htxincailiao.support.entity.HTCustomerSupport;
import org.jeecg.modules.htxincailiao.support.service.IHTCustomerSupportService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: im_conversation
 * @Author: jeecg-boot
 * @Date: 2023-03-14 11:13:41
 * @Version: V1.0
 */
@Api(tags = "im_conversation")
@RestController
@RequestMapping("/im/iMConversation")
@Slf4j
public class IMConversationController extends JeecgController<IMConversation, IIMConversationService> {
    @Autowired
    private IIMConversationService iMConversationService;

    @Resource
    private IIMUserService iMUserService;


    @Resource
    private ISysUserService sysUserService;


    @Resource
    private IHTCustomerSupportService iHTCustomerSupportService;

    @Resource
    private IHTAccountService accountService;

    /**
     * 获取会话信息
     *
     * @param dto
     * @return
     */
    @AutoLog(value = "im_conversation-获取会话信息")
    @ApiOperation(value = "im_conversation-获取会话信息", notes = "im_conversation-获取会话信息")
    @PostMapping(value = "/getConversation")
    public Result<?> getConversation(@Valid @RequestBody IMConversationDTO dto) {
        String ownerId = dto.getOwnerId().trim();
        String targetId = dto.getTargetId().trim();
        log.info("\n\ntargetId : {}\n\n", targetId);

        IMConversation conversation = iMConversationService.queryBy(ownerId, targetId);
        if (oConvertUtils.isEmpty(conversation)) {
            conversation = new IMConversation();
            BeanUtils.copyProperties(dto, conversation);

            IMUser owner = iMUserService.queryByUserId(ownerId);
            if (oConvertUtils.isEmpty(owner)) {
                owner = new IMUser();

                HTPlatformUser platformUser = accountService.queryUserById(ownerId);
                BeanUtils.copyProperties(platformUser, owner);
                if (oConvertUtils.isEmpty(platformUser.getNickname())) {
                    owner.setNickname(platformUser.getPhoneNumber());
                }

                try {
                    owner.setId(null);
                    owner.setUserId(platformUser.getId());
                    iMUserService.save(owner);
                } catch (Exception e) {
                    throw new JeecgBootException("构建owner im user 失败");
                }
            }

            if (oConvertUtils.isNotEmpty(owner.getNickname())) {
                conversation.setOwnerNickname(owner.getNickname());
            } else if (oConvertUtils.isNotEmpty(owner.getUsername())) {
                conversation.setOwnerNickname(owner.getUsername());
            }

            conversation.setOwnerAvatar(owner.getAvatar());

            IMUser receiverUser = iMUserService.queryByUserId(targetId);
            HTCustomerSupport support = iHTCustomerSupportService.queryBySysUserId(targetId);
            if (oConvertUtils.isEmpty(support)) {
                throw new JeecgBootException("客服账户不存在");
            }

            Boolean save = false;
            if (oConvertUtils.isEmpty(receiverUser)) {
                save = true;
                receiverUser = new IMUser();
            }

            receiverUser.setUserId(support.getSysUserId());
            receiverUser.setAccountType(HTAccountTypeEnum.SYS_USER.getValue());
            receiverUser.setNickname(support.getName());
            if (oConvertUtils.isNotEmpty(support.getAvatar())) {
                receiverUser.setAvatar(support.getAvatar());
            }

            SysUser sysUser = sysUserService.getUserById(targetId);
            if (oConvertUtils.isEmpty(sysUser)) {
                throw new JeecgBootException("客服账户管理账户异常");
            }
            receiverUser.setUsername(sysUser.getUsername());
            if (oConvertUtils.isNotEmpty(sysUser.getPassword())) {
                receiverUser.setPassword(sysUser.getPassword());
            }

            if (save) {
                try {
                    iMUserService.save(receiverUser);
                } catch (Exception e) {
                    throw new JeecgBootException("创建客服用户失败");
                }
            }

            log.info("\n\nreceiverUser : {}\n\n", receiverUser);

            if (oConvertUtils.isNotEmpty(receiverUser.getNickname())) {
                conversation.setTargetNickname(receiverUser.getNickname());
            }

            if (oConvertUtils.isNotEmpty(receiverUser.getAvatar())) {
                conversation.setTargetAvatar(receiverUser.getAvatar());
            }

            conversation.setCryptoKey(CryptoUtil.generateKey());
            conversation.setCryptoIv(CryptoUtil.generateIV());

            iMConversationService.save(conversation);
        }

        return Result.OK(conversation);
    }


    /**
     * 分页列表查询
     *
     * @param iMConversation
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "im_conversation-分页列表查询")
    @ApiOperation(value = "im_conversation-分页列表查询", notes = "im_conversation-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(IMConversation iMConversation,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<IMConversation> queryWrapper = QueryGenerator.initQueryWrapper(iMConversation, req.getParameterMap());
        Page<IMConversation> page = new Page<IMConversation>(pageNo, pageSize);
        IPage<IMConversation> pageList = iMConversationService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param iMConversation
     * @return
     */
    @AutoLog(value = "im_conversation-添加")
    @ApiOperation(value = "im_conversation-添加", notes = "im_conversation-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody IMConversation iMConversation) {
        iMConversationService.save(iMConversation);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param iMConversation
     * @return
     */
    @AutoLog(value = "im_conversation-编辑")
    @ApiOperation(value = "im_conversation-编辑", notes = "im_conversation-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody IMConversation iMConversation) {
        iMConversationService.updateById(iMConversation);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "im_conversation-通过id删除")
    @ApiOperation(value = "im_conversation-通过id删除", notes = "im_conversation-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        iMConversationService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "im_conversation-批量删除")
    @ApiOperation(value = "im_conversation-批量删除", notes = "im_conversation-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.iMConversationService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "im_conversation-通过id查询")
    @ApiOperation(value = "im_conversation-通过id查询", notes = "im_conversation-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        IMConversation iMConversation = iMConversationService.getById(id);
        if (iMConversation == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(iMConversation);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param iMConversation
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, IMConversation iMConversation) {
        return super.exportXls(request, iMConversation, IMConversation.class, "im_conversation");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, IMConversation.class);
    }

}
